using B.S.RbacData.Infrastructure;
using B.S.RbacData.Write.API;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using NLog.Web;
using System.Reflection;
using System.Text;
using ServiceManagement.Consul;

var builder = WebApplication.CreateBuilder(args);

//注册consul
builder.Configuration.Register();
// Add services to the container.
//连接数据库上下文
builder.Services.AddDbContext<DataDbcontext>(x =>
{

    x.UseSqlServer(builder.Configuration.GetConnectionString("conn"));
});
//注册中介者
builder.Services.AddMediatR(x => x.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
//注册automapper
builder.Services.AddAutoMapper(typeof(AutoMapperProFiles));
//注册仓储
builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
//注册Nlog
builder.Host.UseNLog();
//配置请求上下文
builder.Services.AddHttpContextAccessor();

// 配置JWT认证
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
var secretKey = Encoding.UTF8.GetBytes(jwtSettings["SecretKey"]);

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(secretKey),
        ValidateIssuer = true,
        ValidIssuer = jwtSettings["Issuer"],
        ValidateAudience = true,
        ValidAudience = jwtSettings["Audience"],
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    };
});

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
// 配置Swagger
builder.Services.AddSwaggerGen(o =>
{

    // 显示 授权信息
    o.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme()
    {
        Description = "添加JWT授权Token：Bearer Token值",
        Name = "Authorization",
        In = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    o.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
{
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[]
            {

            }
        }
});

    var pname = typeof(Program).Assembly.GetName().Name;

    var path = AppDomain.CurrentDomain.BaseDirectory + pname + ".xml";


    o.IncludeXmlComments(path, true);




});

var app = builder.Build();
//跨域
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

//静态资源库放访问文件
app.UseStaticFiles();

// 添加认证中间件
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
